package view;

import java.awt.KeyboardFocusManager;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.StringTokenizer;

import javax.swing.JFileChooser;
import javax.swing.filechooser.FileFilter;

import controle.AtalhosListener;



public class SalvarArquivo {
	
	private static JFileChooser chooser;

	public static String salvar(String nomeArq, String texto) {	
			if (chooser == null) {
				chooser = new JFileChooser();
				chooser.setFileFilter(new FileFilter() {
					
					@Override
					public String getDescription() {
						return ".txt";
					}
					
					@Override
					public boolean accept(File arq) {
						return arq.getName().endsWith(".txt") || arq.isDirectory();
					}
				});
			}
			KeyboardFocusManager.getCurrentKeyboardFocusManager().removeKeyEventDispatcher(AtalhosListener.getInstancia());
			if(texto != null){
				if(nomeArq == null){
					if (chooser.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) {
					    nomeArq = chooser.getSelectedFile().getAbsolutePath() + ".txt";
					    return salva(nomeArq, texto);
					} else {
						KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(AtalhosListener.getInstancia());
						return null;
					}
				} 
				KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(AtalhosListener.getInstancia());
				return salva(nomeArq, texto);
			}
		KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(AtalhosListener.getInstancia());
		return null;
	}

	private static String salva(String nomeArq, String texto) {
		try {
			String linhas[] = texto.split("\n");
			System.out.println(linhas.length);
			
			PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(nomeArq)));  
			for(String linha : linhas){
				out.println(linha);
			}
			out.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return nomeArq;
	}
}
